package com.ruoyi.zq.service.impl;


import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.exception.ServiceException;

import com.ruoyi.common.exception.job.TaskException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.zq.domin.vo.VolunteerActivityVO;
import com.ruoyi.common.zq.mapper.EntryBlankMapper;
import com.ruoyi.common.zq.utils.CommonUtils;
import com.ruoyi.common.zq.utils.TimeUtils;
import com.ruoyi.common.zq.domin.ZqVolunteerActivity;
import com.ruoyi.common.zq.enums.SubscriberType;
import com.ruoyi.common.zq.mapper.ZqVolunteerActivityMapper;
import com.ruoyi.quartz.domain.SysJob;
import com.ruoyi.quartz.service.ISysJobService;
import com.ruoyi.system.service.ISysDeptService;
import com.ruoyi.zq.domin.dto.ZqNoticeDTO;
import com.ruoyi.zq.mapper.CommonUtilsMapper;
import com.ruoyi.zq.service.VolunteerActivityService;
import com.ruoyi.zq.service.ZqNoticeService;
import org.apache.commons.lang3.ObjectUtils;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @Author: LoneyFeather
 * @Date: Created in 15:48 2021/12/24
 */
@Service
public class VolunteerActivityServiceImpl extends ServiceImpl<ZqVolunteerActivityMapper, ZqVolunteerActivity> implements VolunteerActivityService {

    private static final Logger logger = LoggerFactory.getLogger(VolunteerActivityServiceImpl.class);

    @Autowired
    private ZqVolunteerActivityMapper activityMapper;
    @Autowired
    private EntryBlankMapper entryBlankMapper;

    @Autowired
    private CommonUtilsMapper commonUtilsMapper;

    @Autowired
    private ISysJobService sysJobService;

    @Autowired
    private ZqNoticeService zqNoticeService;

    @Autowired
    private ISysDeptService deptService;
    /**
     * 查询活动列表
     * @param activityDTO
     * @return
     */
    @Override
    public List<VolunteerActivityVO> activityList(VolunteerActivityVO activityDTO) {
        // 进行查询时，，dept查询的条件
        List<Long> deptIdList = new ArrayList<>();

        //学生用户(common)只有查看state为1的数据
        List<String> roleKeys = commonUtilsMapper.roleKey(SecurityUtils.getUserId());
        boolean isSutdent = CommonUtils.onlyCommon(roleKeys);
        if (isSutdent){
            activityDTO.setState("1");
            if (activityDTO.getDeptId() == null){
                deptIdList.add(100L);
                deptIdList.add(SecurityUtils.getDeptId());
            }
        }

        if (activityDTO.getDeptId() != null){
            deptIdList.add(activityDTO.getDeptId());
        }
        activityDTO.setDeptIds(deptIdList.stream().toArray(Long[]::new));

        return activityMapper.selectListByVO(activityDTO);
    }

    @Override
    public VolunteerActivityVO getInforByActivityId(Long activityId) {
        if (activityId==null || activityId == 0){
            throw new ServiceException("请传入正确的数据！！！");
        }
        return activityMapper.getByActivityId(activityId);
    }

    /**
     * 添加活动数据
     * @param activityDTO
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int addActivity(ZqVolunteerActivity activityDTO) throws TaskException, SchedulerException {
        if (activityDTO.getBeginTime().after(activityDTO.getEndTime())){
            throw new ServiceException("开始时间和结束时间有问题");
        }
        activityMapper.insert(activityDTO);

//        if (activityDTO.getBeginTime().after(activityDTO.getCreateTime())){
            SysJob sysJob = getSysJob(activityDTO);
            sysJob.setJobName("开启该活动报名【"+activityDTO.getActivityName()+"】");
            sysJob.setCronExpression(TimeUtils.dateConvertCron(activityDTO.getBeginTime()));
            sysJob.setInvokeTarget("volunteerActiveTask.openActivity(" +activityDTO.getActivityId()+ "L)" );
            sysJobService.insertJob(sysJob);
            logger.warn("添加定时任务：{}"+sysJob.toString());
//        }
        //关闭报名接口
        SysJob sysJobClose = getSysJob(activityDTO);
        sysJobClose.setJobName("关闭该活动的报名【"+activityDTO.getActivityName()+"】");
        sysJobClose.setCronExpression(TimeUtils.dateConvertCron(activityDTO.getEndTime()));
        sysJobClose.setInvokeTarget("volunteerActiveTask.closeActivity(" +activityDTO.getActivityId()+ "L)" );
        sysJobService.insertJob(sysJobClose);
        logger.warn("添加定时任务（关闭报名接口）：{}"+sysJobClose.toString());

        //TODO 自动完成活动（修改状态）的定时任务。

        //添加公告
        Long deptId= SecurityUtils.getDeptId();
        SysDept dept = deptService.selectDeptById(deptId);
        if (ObjectUtils.isEmpty(dept)){
            throw new ServiceException("部门数据出现错误："+ deptId);
        }

        ZqNoticeDTO noticeDTO = new ZqNoticeDTO();
        if (activityDTO.getDeptId() == 100){
            noticeDTO.setSubscriberType(SubscriberType.ALL.name());
            noticeDTO.setNoticeTitle("【"+dept.getDeptName()+ "】 发布新的志愿服务活动（全校同学均可参与）");
        }else {
            noticeDTO.setSubscriberType(SubscriberType.DEPT.name());
            noticeDTO.setNoticeTitle("【"+dept.getDeptName()+ "】 发布新的志愿服务活动（仅限本学院的同学参与）");
        }
        noticeDTO.setNoticeContent("【"+activityDTO.getActivityName()+"】"+"活动将于"+TimeUtils.yyyyMMddHHmmss(activityDTO.getBeginTime()) +
                "--"+TimeUtils.yyyyMMddHHmmss(activityDTO.getEndTime()) +"时间范围内进行报名；<br>"+
                "具体信息请查看活动详情页！！！");

        noticeDTO.setStatus("0");
        noticeDTO.setNoticeType("2");
        noticeDTO.setCreateBy(activityDTO.getCreateBy());
        noticeDTO.setCreateTime(activityDTO.getCreateTime());

        zqNoticeService.addNoticeAndDetails(noticeDTO);
        logger.info("添加志愿活动发布公告成功：{}",noticeDTO.toString());

        return 1;
    }

    /**
     * 修改活动信息
     * @param activity
     * @return
     */
    @Override
    public int updateAtivity(ZqVolunteerActivity activity) {

        return activityMapper.updateById(activity);
    }

    @Override
    public Boolean controlByActivityId(Long activityId) {
        ZqVolunteerActivity activity = activityMapper.selectById(activityId);
        //创建者可以有权限（名字）//部门为最高级的有权限
        if (!SecurityUtils.getUsername().equals(activity.getCreateBy())&&SecurityUtils.getDeptId() != 100){
            return false;
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int removeActivity(Long[] activityIds) {

        //已完成的活动不能删除
        Integer count = activityMapper.countApplyState(activityIds);
        if (count>0){
            logger.info("选中的活动数据存在已完成的数据，无法进行删除！！！");
            throw new ServiceException("选中的活动数据存在已完成的数据，无法进行删除！！！");
        }

        // 删除报名表
        entryBlankMapper.updateIsDelByActivityIds(activityIds);
        logger.info("逻辑删除报名表: "+activityIds.toString());

        //TODO 删除数据表

        return activityMapper.updateIsDelByActivityIds(activityIds);
    }

    /**
     * 定时任务通用的添加
     * @param activity
     * @return
     */
    private SysJob getSysJob(ZqVolunteerActivity activity){
        SysJob sysJob = new SysJob();
        //DEFAULT
        sysJob.setJobGroup("SYSTEM");
        sysJob.setMisfirePolicy("2");
        sysJob.setConcurrent("1");
        sysJob.setStatus("0");
        sysJob.setCreateBy(SecurityUtils.getUsername());
        sysJob.setCreateTime(activity.getCreateTime());
        return sysJob;
    }
}
